<script lang="ts" setup>
    import axios from 'axios';
    import { onMounted, ref } from 'vue';
    import { useRouter } from 'vue-router';

    let bookData = ref(null)
    let router = useRouter()
    let formData = ref({
      name:"",
      type:""
    })
  
    async function getBookList() {
      const res = await axios.get("http://localhost:8080/api/books",{
        headers:{
          "Authorization": "Bearer " + localStorage.getItem("token")
        }
      })
      bookData.value = res.data
    }
    onMounted(getBookList)
    async function handleDetailClick(data:any){
        router.push({
          path:"/details",
          query:{
            id:data.row.id
          }
        })
    }
    function submit(){
      console.log(formData.value)
      axios.get("http://localhost:8080/api/books/search",{
        params:formData.value
      }).then((res) => {0
        bookData.value = res.data
      })
    }
    
    
    async function handleDeleteClick(data:any){
        await axios.delete("http://localhost:8080/api/books/"+data.row.id,{
            headers:{
                "Authorization": "Bearer " + localStorage.getItem("token")
            }
        })
        getBookList()
    }

    async function handleEditClick(data:any){
        router.push({
          path:"/update",
          query:{
            id:data.row.id
          }
        })
    }
    async function handleAddClick(){
      router.push({
        path:"/add"
      })
    }
</script>

<template>
  <h1>书籍管理</h1>
  <form action="">
      书名：<input type="text" v-model="formData.name">
      类型：<input type="text" v-model="formData.type">
      <el-button type="primary" style="margin-left: 10px;" size="small" @click="submit">搜索</el-button>
  </form>
  <div class="list">
    <el-table :data="bookData" style="width: 100%">
        <el-table-column prop="id" label="序号" width="180" />
        <el-table-column prop="name" label="书名" width="180" />
        <el-table-column prop="type" label="类型" />

        <el-table-column label="操作">
          <template #default="data">
            <el-button type="primary" @click="handleDetailClick(data)">详情</el-button>
            <el-button type="primary" @click="handleEditClick(data)">编辑</el-button>
            <el-button type="danger" @click="handleDeleteClick(data)">删除</el-button>
          </template>
        </el-table-column>
    </el-table>
    <el-button type="primary" @click="handleAddClick">添加</el-button>
  </div>
    
</template>

<style scoped>

</style>